package com.example.rfidwms;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.zebra.rfid.api3.TagData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class InTagActivity extends AppCompatActivity {

    public TextView statusTextViewRFID = null;
    RFIDHandler rfidHandler;
    private Map<String, TagData> dataMap = new HashMap<>();
    //    读取到标签数
    private TextView textViewReadNum;
    //    成功上传的标签数
    private TextView textViewUploadNum;
    private TextView textViewdata;

    //    全局变量，得到用户所在仓库
    private Application app = new Application();

    //    请求体
    private FormBody formBody;
    //    得到request返回值
    private String data;
    //    存储request返回的json数据
//    private List<Map<String,Object>> list=new ArrayList<>();
    private String tid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        防止布局被输入法顶出去
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_in_tag);

        statusTextViewRFID = findViewById(R.id.statusTextViewRFID);
        textViewReadNum = findViewById(R.id.textView_readNum);
        textViewUploadNum = findViewById(R.id.textView_uploadNum);
        textViewdata = (TextView) findViewById(R.id.textViewdata);

        rfidHandler = new RFIDHandler();
        rfidHandler.onCreate(this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        rfidHandler.onPause();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        String status = rfidHandler.onResume();
        statusTextViewRFID.setText(status);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rfidHandler.onDestroy();
    }

    public void handleTagdata(TagData[] tagData) {
        for (int index = 0; index < tagData.length; index++) {
            if (tagData[index].getMemoryBankData() != null && tagData[index].getTagID().startsWith("AAAA")) {
//                读取标签，以AAAA开头合法，放入哈希表去重
                dataMap.put(tagData[index].getMemoryBankData(), tagData[index]);
            }
        }
    }

    public void handleTriggerPress(boolean pressed) {
        if (pressed) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dataMap.clear();//清空map
                    textViewdata.setText("");
                }
            });
            rfidHandler.performInventory();
        } else {
            rfidHandler.stopInventory();
//            把显示放到这里不会重复显示
            final StringBuilder sb = new StringBuilder();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    显示读取的标签数
                    textViewReadNum.setText(String.valueOf(dataMap.size()));
                    textViewUploadNum.setText("");
                    for (Map.Entry<String, TagData> entry : dataMap.entrySet()) {
//                        sb.append(entry.getValue().getTagID()+ "\n");
                        if (app.materialMap.keySet().contains(entry.getValue().getTagID())) {
                            try {
                                sb.append(app.materialMap.get(entry.getValue().getTagID()).getString("id") + "  " + app.materialMap.get(entry.getValue().getTagID()).getString("name") + "  " + app.materialMap.get(entry.getValue().getTagID()).getString("specs") + "\n");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            sb.append(entry.getValue().getTagID() + "\n");
                        }
                    }
                    textViewdata.append(sb.toString());
                }
            });
        }
    }

    public void tag_match(View view) {
//        list.clear();
//        清空读取显示
        textViewdata.setText("");
        //得到登录用户的仓库信息,进行非空判断
        if (TextUtils.isEmpty(String.valueOf(app.dpt_id))) {
            Toast.makeText(this, "需要用户所在仓库号", Toast.LENGTH_SHORT).show();
            return;
        } else {
            OkHttpClient client = new OkHttpClient();
            formBody = new FormBody.Builder()
                    .add("dpt_id", app.dpt_id)
                    .build();
//        根据仓库号读取数据库的请求
            new Thread(() -> {
                Request request = new Request.Builder().post(formBody).url(app.path_instock).build();
                try {
                    Response response = client.newCall(request).execute();
                    data = response.body().string();
                    //解析
                    if (data != null) {
                        try {
                            JSONArray array = new JSONArray(data);
                            final StringBuilder sb = new StringBuilder();
                            String content;
//                查询视图中已经入库的产品
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject object = array.getJSONObject(i);
                                tid = object.getString("tid");
//在扫码枪读取的结果里剔除掉已经入库的
                                if (dataMap.keySet().contains(tid)) {
//显示已经在库
                                    content = "已在库  " + object.getString("name") + "  " + object.getString("classify_num") + "  " + object.getString("specs");
                                    sb.append(content + "\n");
                                    dataMap.remove(tid);
                                }
                            }
                            for (Map.Entry<String, TagData> entry : dataMap.entrySet()) {
                                //显示可以上传
//                                sb.append("可入库  " + entry.getValue().getTagID() + "\n");
                                if (app.materialMap.keySet().contains(entry.getValue().getTagID())) {
                                    try {
                                        sb.append("可入库  " + app.materialMap.get(entry.getValue().getTagID()).getString("id") + "  " + app.materialMap.get(entry.getValue().getTagID()).getString("name") + "  " + app.materialMap.get(entry.getValue().getTagID()).getString("specs") + "\n");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    sb.append("无信息  " + entry.getValue().getTagID() + "\n");
                                }
                            }

                            runOnUiThread(() -> {
                                textViewdata.append(sb.toString());
                                //                显示上传数
                                textViewUploadNum.setText(String.valueOf(dataMap.size()));
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }


    //    确认上传按钮
    public void upload(View view) {
        //                上传扫码数据
        uploadJson(dataMap);
    }

    private void uploadJson(Map<String, TagData> dataMap) {
        if (dataMap.size() != 0) {
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");

            JSONArray array = new JSONArray();
//将每个扫描结果放到json数组中
            for (Map.Entry<String, TagData> entry : dataMap.entrySet()) {
                JSONObject object = new JSONObject();
                try {
                    object.put("tid", entry.getValue().getMemoryBankData());
                    object.put("epc", entry.getValue().getTagID());
                    object.put("act", "Y");
                    object.put("user_id", Integer.valueOf(app.user_id));
                    object.put("dpt_id", Integer.valueOf(app.dpt_id));
                    array.put(object);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            //创建一个OkHttpClient对象
            OkHttpClient okHttpClient = new OkHttpClient();
            //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
            RequestBody requestBody = RequestBody.create(JSON, array.toString());
            //创建一个请求对象
            Request request = new Request.Builder()
                    .url(app.path_bulk_insert)
                    .post(requestBody)
                    .build();

            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.i("log", "onFailure: " + e);
                    runOnUiThread(() -> {
                        Toast.makeText(InTagActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.i("log", "onResponse: " + response.body().string());
                    runOnUiThread(() -> {
                        Toast.makeText(InTagActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                    });
                }
            });
        }
    }

}